package com.poizon.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.poizon.config.SystemConfig;

import java.io.ByteArrayInputStream;
import java.util.Date;

/**
 * @ClassName OssUtils
 * @Author NoCheng
 * @Date 2022/1/2 10:31
 * @Description:TODO 阿里云对象存储工具
 */

public class OssUtils {
    //bucket 所在地域对应的 endpoint
    private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
    //bucket 名字
    private static final String bucket="data2112";

    // 创建OSSClient实例。
    public static final OSS ossClient ;
    static {
        ossClient= new OSSClientBuilder().build(endpoint, SystemConfig.ALI_KEY, SystemConfig.ALI_SEC);
    }
    /**
     * 实现资源上传，并返回访问路径*/
    public static String upload(String obj, byte[] data, Date date){
        //1.实现资源上传
        ossClient.putObject(bucket, obj, new ByteArrayInputStream(data));
        //2.生成访问路径
        return ossClient.generatePresignedUrl(bucket, obj, date).toString();
    }
    /**
     * 实现资源的删除*/
    public static boolean delete(String obj){
        try{
            ossClient.deleteObject(bucket, obj);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    /**
     * 验证资源是否存在*/
    public static boolean exists(String obj){
        return ossClient.doesObjectExist(bucket, obj);
    }
    /**
     * 创建对象的访问链接*/
    public static String createUrl(String obj, Date date){
        return ossClient.generatePresignedUrl(bucket, obj, date).toString();
    }
}
